package com.yl.nettylearning.day02;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @author yangl
 * Scattering：将数据写入到buffer时，可以采用buffer数组依次写入[分散]
 * Gathering：从buffer读取数据时，也可以采用buffer数组依次读
 */
public class ScatteringAndGatheringTest {
    public static void main(String[] args) throws Exception{
        //使用ServerSocketChannel和SocketChannel网络
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);
        //绑定端口到socket，并启动
        serverSocketChannel.socket().bind(inetSocketAddress);
        //创建buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(2);
        byteBuffers[1] = ByteBuffer.allocate(3);

        //等待客户端连接
        SocketChannel socketChannel = serverSocketChannel.accept();
        //假定从客户端读取8个字节
        int messageLength = 8;
        //循环读取
        while (true){
            int byteRead = 0;
            if(byteRead < messageLength){
                long read = socketChannel.read(byteBuffers);
                byteRead += read;
                System.out.println("byteRead = " + byteRead);
                //使用流打印，看看当前的这个流的position和limit
                Arrays.asList(byteBuffers).stream().map(buffer -> "position=" + buffer.position()
                    + "limit=" + buffer.limit()
                ).forEach(System.out::print);
            }
            //将所有的buffer反转
            Arrays.asList(byteBuffers).forEach(buffer -> buffer.flip());

            //将数据读取显示
            long byteWrite = 0;
            while (byteWrite < messageLength){
                long write = socketChannel.write(byteBuffers);
                byteWrite += write;
            }

            //将所有的buffer复位
            Arrays.asList(byteBuffers).forEach(buffer -> buffer.clear());
            System.out.println("byteRead:=" + byteRead + " byteWrite:=" + byteWrite + " messageLength:=" + messageLength);
        }
    }
}
